//
//  JaMoDecomposition.m
//  kscode
//
//  Created by 권오상 on 11. 8. 20..
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "JaMoDecomposition.h"


@implementation JaMoDecomposition

- (id) init
{
	if (self = [super init])
	{
		hanTable = [NSArray arrayWithObjects:@"ㄱㄲㄴㄷㄸㄹㅁㅂㅃㅅㅆㅇㅈㅉㅊㅋㅌㅍㅎ",		//19 초성
					@"ㅏㅐㅑㅒㅓㅔㅕㅖㅗㅘㅙㅚㅛㅜㅝㅞㅟㅠㅡㅢㅣ",							//21 중성
					@" ㄱㄲㄳㄴㄵㄶㄷㄹㄺㄻㄼㄽㄾㄿㅀㅁㅂㅄㅅㅆㅇㅈㅊㅋㅌㅍㅎ", nil];			//28 종성
	}
	
	return self;
}
/** 
 * 복모음, 복자음 처리 
 */ 
-(NSString*)doubleCharConvertor:(NSString*)c {	
	
	if ([c isEqualToString:@"ㄳ"]){
		return @"ㄱㅅ";
	}else if ([c isEqualToString:@"ㄵ"]){
		return @"ㄴㅈ";
	}else if ([c isEqualToString:@"ㄶ"]){
		return @"ㄴㅎ";
	}else if ([c isEqualToString:@"ㄺ"]){
		return @"ㄹㄱ";
	}else if ([c isEqualToString:@"ㄻ"]){
		return @"ㄹㅁ";
	}else if ([c isEqualToString:@"ㄼ"]){
		return @"ㄹㅂ";
	}else if ([c isEqualToString:@"ㄽ"]){
		return @"ㄹㅅ";
	}else if ([c isEqualToString:@"ㄾ"]){
		return @"ㄹㅌ";
	}else if ([c isEqualToString:@"ㄿ"]){
		return @"ㄹㅍ";
	}else if ([c isEqualToString:@"ㅀ"]){
		return @"ㄹㅎ";
	}else if ([c isEqualToString:@"ㅄ"]){
		return @"ㅂㅅ";
	}else if ([c isEqualToString:@"ㅘ"]){
		return @"ㅗㅏ";
	}else if ([c isEqualToString:@"ㅙ"]){
		return @"ㅗㅐ";
	}else if ([c isEqualToString:@"ㅚ"]){
		return @"ㅗㅣ";
	}else if ([c isEqualToString:@"ㅝ"]){
		return @"ㅜㅓ";
	}else if ([c isEqualToString:@"ㅞ"]){
		return @"ㅜㅔ";
	}else if ([c isEqualToString:@"ㅟ"]){
		return @"ㅜㅣ";
	}else if ([c isEqualToString:@"ㅢ"]){
		return @"ㅡㅣ";
	}
	
	return c;
}

-(NSString*)decomposition:(NSString*)text
{
	NSString *output = @"";
	
	for (NSUInteger i=0; [text length] > i; i++) {
		
		unichar c = [text characterAtIndex:i];
		
		//only for hangul
		if (c >= 0xAC00 && c <= 0xD7A3)
		{
			int unicode = c-0xAC00;
			
			NSUInteger seong[3];
			seong[0] = unicode / (21 * 28);				//초성 
			seong[1] = (unicode % (21 * 28)) / 28;		//중성 
			seong[2] = unicode % 28;					//종성
			NSLog(@"%i, %i, %i", seong[0], seong[1], seong[2]);
			
			int count = 3;
			unichar alphabet[count];		
			for (int j = 0; count > j; j++) {
				alphabet[j] = [[hanTable objectAtIndex:j] characterAtIndex:seong[j]];
				
				NSString *toString = [Utillity unicharToString:alphabet[j]];
				//받침 없는 종성 상태
				if (j == 2 && [toString isEqualToString:@" "]) {
					continue;
				}
				
				output = [output stringByAppendingString:
						  [self doubleCharConvertor:toString]];
			}
		}else {
			output = [output stringByAppendingString:[Utillity unicharToString:c]];
		}

	}
	NSLog(@"finish : '%@'", output);
	return output;
}

- (void)dealloc
{
	if (hanTable != nil) {
		[hanTable release];
	}
	[super dealloc];
}
@end
